import {
	func
} from "../uni_modules/uview-plus/libs/function/test";

var xaoi = {};

xaoi.time = function(o) {
	var t = o || new Date();
	return parseInt(t.getTime() / 1000);
}

xaoi.date = function(str) {
	var t;
	switch (arguments.length) {
		case 1:
			t = new Date();
			break;
		case 2:
			if (Object.prototype.toString.call(arguments[1]) === '[object Date]') {
				t = arguments[1];
			} else if (typeof arguments[1] === 'number' && arguments[1].toString().length > 10) {
				t = new Date(arguments[1]);
			} else if (arguments[1] >= 0) {
				t = new Date(parseInt(arguments[1] + '000'));
			} else if (arguments[1] < 0) {
				t = Math.abs(arguments[1]);
				var d = parseInt(t / 60 / 60 / 24);
				var H = parseInt(t / 60 / 60 % 24);
				var i = parseInt(t / 60 % 60);
				var s = parseInt(t % 60);
				str = str.replace(/d([^dHis]*)/g, d > 0 ? d + '$1' : '');
				str = str.replace(/H([^dHis]*)/g, H > 0 ? H + '$1' : d > 0 ? '0' : '');
				str = str.replace(/i([^dHis]*)/g, i > 0 ? i + '$1' : d > 0 || H > 0 ? '0' : '');
				str = str.replace(/s([^dHis]*)/g, s > 0 ? s + '$1' : d > 0 || H > 0 || i > 0 ? '0' : '');
				return str;
			} else {
				return '';
			}
			break;
	}
	var Y = t.getFullYear();
	var y = t.getFullYear().toString().substr(2);
	var m = t.getMonth() + 1;
	var d = t.getDate();
	var H = t.getHours();
	var i = t.getMinutes();
	var s = t.getSeconds();
	if (m < 10) m = '0' + m;
	if (d < 10) d = '0' + d;
	if (H < 10) H = '0' + H;
	if (i < 10) i = '0' + i;
	if (s < 10) s = '0' + s;
	str = str.replace(/Y/g, Y);
	str = str.replace(/y/g, y);
	str = str.replace(/m/g, m);
	str = str.replace(/d/g, d);
	str = str.replace(/H/g, H);
	str = str.replace(/i/g, i);
	str = str.replace(/s/g, s);
	return str;
}

xaoi.strtotime = function(str) {
	if (!str) return 0
	var _arr = str.split(' ');
	var _day = _arr[0].split('-');
	_arr[1] = (_arr[1] == null) ? '0:0:0' : _arr[1];
	var _time = _arr[1].split(':');
	for (var i = _day.length - 1; i >= 0; i--) {
		_day[i] = isNaN(parseInt(_day[i])) ? 0 : parseInt(_day[i]);
	};
	for (var i = _time.length - 1; i >= 0; i--) {
		_time[i] = isNaN(parseInt(_time[i])) ? 0 : parseInt(_time[i]);
	};
	var _temp = new Date(_day[0], _day[1] - 1, _day[2], _time[0], _time[1], _time[2]);
	return _temp.getTime() / 1000;
}

//拦截器
xaoi.call = function() {

	function object_clone(a) {
		if (typeof a !== 'object' || a === null) return a;
		const b = Array.isArray(a) ? [] : {};
		for (const key in a) b[key] = object_clone(a[key]);
		return b;
	}

	var fn = function() {
		var args = [];
		for (var i in arguments) args.push(arguments[i]);

		var that = object_clone(this);
		if (args.length && typeof args[0] === 'function') {
			that.req.push(args[0])
			if (args.length >= 2 && typeof args[1] === 'function') that.res.push(args[1]);
			return fn.bind(that)
		} else {
			that.args = args;
			var f = function(d, h) {
				if (d.length) {
					var p = d.splice(0, 1)[0].apply(that, that.args)
					Promise.resolve(p).then(function(x) {
						typeof x !== 'undefined' ? h(x) : f(d, h)
					}).catch(h)
				} else {
					h.apply(that, that.args)
				}
			}
			return new Promise(function(ok) {
				f(that.req, function(d) {
					that.args = [d];
					f(that.res, function(d) {
						ok(d)
					})
				});
			})
		}
	}

	return fn.bind({
		req: [],
		res: []
	});
}()

xaoi.ajax = xaoi.call(function(url, data, handle) {
	var req = {
		method: 'post',
		url: url,
		params: '',
		data: data,
		headers: {},
		handle,
		withCredentials: false,
	}

	this.req = req;

	this.http = function(req) {
		return new Promise(ok => {
			var xhr = new XMLHttpRequest();
			xhr.open(req.method, req.url);
			for (var i in req.headers) xhr.setRequestHeader(i, req.headers[i]);
			xhr.addEventListener('load', function() {
				if (xhr.readyState == 4) {
					if (xhr.status == 200) {
						var t
						try {
							t = JSON.parse(xhr.responseText);
						} catch (ex) {
							ok({
								code: 500
							});
							return;
						}
						ok(t);
					} else {
						ok({
							code: 404
						});
					}
				}
			});
			xhr.send(req.data);
		})
	}
}, function() {
	return new Promise(ok => {
		var that = this;

		var onhandle = function(data) {
			if (typeof that.req.handle == 'function') {
				Promise.resolve(that.req.handle.call(that, data)).then((d) => {
					if (d) {
						that.args = [d]
						ok()
					}
				})
			} else {
				that.args = [data]
				ok()
			}
		}

		this.http({
			...this.req,
			header: this.req.headers
		}).then(function(res) {
			that.res = res;

			onhandle(res.data)
		}, function(error) {
			console.error(error)
			onhandle({
				code: 404,
				data: error,
				message: '请求失败'
			})
		})
	})
})

/**
 * 延时等待
 * 创建
 * 	var onok = xaoi.ele()
 * 
 * 添加监听
 * 	await onok()
 * 
 * 执行ok
 * 	onok(1)
 * @returns function
 */
xaoi.ele = function() {
	var is_ok = false;
	var lis = [];
	var _d;
	return function(d) {
		if (arguments.length) {
			_d = d
			is_ok = true;
			for (var i in lis) lis[i](_d);
			lis = []
		} else {
			return new Promise(function(ok) {
				if (is_ok) {
					ok(_d);
				} else {
					lis.push(ok)
				}
			})
		}
	}
}

/**
 * 发送事件
 * xaoi.event('add',{})
 * 
 * 接收事件
 * var index = xaoi.event.on('add',d=>{})
 * var index = xaoi.event.on(['add','edit'],d=>{})
 * 
 * 取消接收事件
 */
xaoi.event = function() {
	var Store = {};
	var unevent = function() {
		if (typeof Store[this._uid] !== 'undefined') {
			delete Store[this._uid]
		}
	}
	return function(vue) {
		if (typeof vue === 'string' || Array.isArray(vue)) {
			var args = [...arguments]
			return new Promise(ok => {
				var name = args.shift();
				var all = [];
				if (name)
					for (var i in Store) {
						if (typeof Store[i][name] !== 'undefined') {
							for (var v2 of Store[i][name]) {
								all.push(Promise.resolve(v2.apply({}, args)))
							}
						}
					}
				Promise.all(all).then(ok)
			})
		} else {
			var destroyed = vue.$options.destroyed
			if (!destroyed.includes(unevent)) destroyed.push(unevent)
			var uid = vue._uid
			Store[uid] = {};
			return function(name, fn) {
				if (typeof Store[uid][name] === 'undefined') Store[uid][name] = [];
				var lis = Store[uid][name];
				lis.push(fn)
				return function() {
					lis.splice(lis.findIndex(v => v === fn), 1)
				}
			}
		}
	}
}();

xaoi.store = function() {
	switch (arguments.length) {
		case 1:
			return uni.getStorageSync(arguments[0])
			break;
		case 2:
			return uni.setStorageSync(arguments[0], JSON.stringify(arguments[1]))
			break;
	}
}

xaoi.on = function(obj, data) {
	for (let i in data) {
		Object.defineProperty(obj, i, {
			value: data[i],
			writable: true,
			configurable: true
		})
	}
}

xaoi.ws = function(url) {
	var ws;
	var fn = function() {
		ws = new WebSocket(url);
		ws.onopen = function(e) {
			if (typeof fn.onopen === 'function') fn.onopen(e)
		};
		ws.onmessage = function(e) {
			var d;
			try {
				d = JSON.parse(e.data);
			} catch (e) {};
			if (d && typeof d[0] !== 'undefined') {
				var k = d.shift();
				if (typeof fn[k] === 'function') fn[k].apply(null, d)
			}
		};
		ws.onerror = function(e) {
			if (typeof fn.onerror === 'function') fn.onerror(e)
		};
		ws.onclose = function(e) {
			if (typeof fn.onclose === 'function') fn.onclose(e)
		};

		fn.send = function() {
			var args = [];
			for (var i in arguments) args.push(arguments[i]);
			if (ws.readyState === 1)
				ws.send(JSON.stringify(args));
			else
				console.log('连接断开，请刷新页面再试！');
		};

		fn.close = function() {
			ws.close();
		};
	}

	return fn;
};


xaoi.toast = function(title, duration = 2000) {
	uni.showToast({
		title: String(title),
		icon: 'none',
		duration
	})
}

xaoi.checkSetting = function(image, type) {
	uni.getSetting({
		success: (res) => {
			if (!res.authSetting['scope.writePhotosAlbum']) {
				uni.authorize({
					scope: 'scope.writePhotosAlbum',
					success: () => {
						if (type == 'canvas') {
							saveCanvasImage(image);
						} else {
							saveImage(image);
						}
					},
					fail: () => {
						uni.showModal({
							title: '提示',
							content: '需要授权保存到相册',
							success: (res) => {
								if (res.confirm) {
									uni.openSetting();
								}
							}
						});
					}
				});
			} else {
				if (type == 'canvas') {
					saveCanvasImage(image);
				} else {
					saveImage(image);
				}
			}
		},
		fail: (err) => {
			console.log(err, '213123123')
		}
	});
}

function saveImage(img) {
	console.log(img)
	uni.getImageInfo({
		src: img,
		success: (res) => {
			var path = res.path;

			uni.saveImageToPhotosAlbum({
				filePath: path,
				success: () => {
					uni.showToast({
						title: '图片已保存',
						icon: 'success'
					});
				},
				fail: (e) => {
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					});
				}
			});
		}
	});

}

function saveCanvasImage(image) {
	console.log(image, 'imageimageimage')
	uni.canvasToTempFilePath({
		canvas: image,
		success: (res) => {
			console.log(res, '1231231231233')
			uni.saveImageToPhotosAlbum({
				filePath: res.tempFilePath,
				success: () => {
					uni.showToast({
						title: '图片已保存',
						icon: 'success'
					});
				},
				fail: (e) => {

					uni.showToast({
						title: '保存失败',
						icon: 'none'
					});
				}
			});
		},
		fail: (e) => {
			console.log(e, 'eeeeeee')
			uni.showToast({
				title: '保存失败',
				icon: 'none'
			});
		}
	})
}

export default xaoi;